#include<iostream>
#include<fcntl.h>
#include <sstream>
#include <string.h>
#include<vector>
#include<fstream>
#include<map>
#include<stdlib.h>
using namespace std;
vector<string> history;
static vector<string>::iterator it;
static string file = "/tmp/.shell_history";	
static bool flag; 
class History {
	public:
	static void loadFile(const char * file) {
		if(!flag) {
			ifstream ifs(file);
			string temp;
			while(getline(ifs, temp)) {
				history.push_back(temp);
			}
			ifs.close();
			flag =1;
		}
	}
	
	static void flush() {
		it = history.begin();
		ofstream myfile(file.c_str());
	 	if (myfile.is_open()) {
			while(it!=history.end()) {
				myfile<<*it;
				myfile<<endl;
				it++;
			}
			myfile.close();
		}
	}
				
				

        static void display() {
		it = history.begin();
		int i=1;
		Utility::out_start();
		while(it != history.end()) {
			cout<<i<<"\t"<<*it<<endl;
			it++;
			i++;
		}
		Utility::out_end();
	}

	static string find(string startwith) {
		loadFile(file.c_str());
		it= history.end();
		it--;
		while(it!=history.begin()) {
			if(Utility::startswith(*it, startwith)) {
				return *it;
			}
			it--;
		}
		return "";
	}
	
	
	static void add(string command) {
		loadFile(file.c_str());
		if(history.size()>1000) {
			history.erase(history.begin());
		}
		if(!Utility::startswith(command, "!")) {
			history.push_back(command);
		}
	}
};
